package com.fc.advbox.service.impl;

import com.fc.advbox.dao.BaseDao;
import com.fc.advbox.dao.EquipmentHoldingDao;
import com.fc.advbox.entity.ContractEntity;
import com.fc.advbox.entity.EquipmentHoldingEntity;
import com.fc.advbox.service.IEquipmentHoldingService;
import com.fc.advbox.utils.Constant;
import com.fc.advbox.utils.DateTimeHelper;
import com.fc.advbox.utils.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * Created by E7450 on 2018/7/2.
 */
@Service("equipmentHoldingService")
public class EquipmentHoldingServiceImpl extends BaseServiceImpl<EquipmentHoldingEntity> implements IEquipmentHoldingService {

    @Autowired
    private EquipmentHoldingDao equipmentHoldingDao;

    @Override
    public BaseDao getDao() {
        return equipmentHoldingDao;
    }

    @Override
    public EquipmentHoldingEntity queryByEquipmentId(Long equipmentId) {
        return equipmentHoldingDao.queryByEquipmentId(equipmentId);
    }

    @Override
    public List<EquipmentHoldingEntity> queryAllCurrentActiveRentHoldings(Map<String, Object> params)
    {
        return equipmentHoldingDao.queryRentActiveListOnCurrent(params);
    }

    @Override
    public void confirmContractToUpdateEquipmentRate(ContractEntity contractEntity) {
        if(contractEntity == null
                || contractEntity.getEquipmentIds() == null
                || contractEntity.getEquipmentIds().isEmpty())
        {
            return;
        }
        if(contractEntity.getAmount() == null)
        {
            //如果本次合同没有金额，则设置合同金额为0
            contractEntity.setAmount(new BigDecimal(0)); // 本次合同金额
        }
        if(contractEntity.getEndDate() == null
                || contractEntity.getStartDate() == null)
        {
            throw new RRException("合同起始、截至时间不能为空!");
        }
        if(contractEntity.getEndDate().before(contractEntity.getStartDate()))
        {
            throw new RRException("合同截至时间不能早于起始时间!");
        }
        updateHoldingRate(contractEntity);
    }

    /**
     * 终止合同时，更新设备收益计算的结束时间
     * @param contractEntity
     */
    @Override
    public void terminateEquipmentRateCalculation(ContractEntity contractEntity) {

        if(contractEntity == null
                || contractEntity.getEquipmentIds() == null
                || contractEntity.getEquipmentIds().isEmpty())
        {
            return;
        }
        updateHoldingRate(contractEntity);
    }

    /**
     * 通过合同总额计算每天，每台设备的收益
     * @param totalAmount  -- 合同总金额
     * @param returnAmount -- 单台机器落地安装返利
     * @param days    -- 合同天数
     * @param equipCount  -- 所租用机器台数
     * @return
     */
    private BigDecimal calculateEachEquipEachDayAmount(BigDecimal totalAmount, BigDecimal returnAmount,  BigDecimal days, BigDecimal equipCount)
    {
        // 计算公式： 每天每台机器的收益 = （广告合同总金额 - 单台返利*机器台数） / 机器台数
        // 结果保留两位小数点，舍去第三位小数点后的数字
        if(returnAmount == null)
        {
            returnAmount = BigDecimal.ZERO;
        }
        return totalAmount.subtract(returnAmount.multiply(equipCount)).divide(equipCount).divide(days, 2, RoundingMode.DOWN);
    }


    /**
     * 根据合同变更holding表
     * @param contractEntity
     */
    private void updateHoldingRate(ContractEntity contractEntity) {
        BigDecimal equipCount = new BigDecimal(contractEntity.getEquipmentIds().size()); // 设备数量
        BigDecimal contractDays = new BigDecimal(DateTimeHelper.calculateDateDiff(contractEntity.getStartDate(), contractEntity.getEndDate())); // 合同天数

        EquipmentHoldingEntity equipmentHolding = new EquipmentHoldingEntity();
        if(Constant.ContractType.AGENT.getValue().equals(contractEntity.getType()))
        {
            equipmentHolding.setAgentOrgId(contractEntity.getYiOrgId());
            equipmentHolding.setAgentOrgName(contractEntity.getYiOrgName());
            equipmentHolding.setAgentRate(contractEntity.getBenifitRate()); // 代理商分成比例
            equipmentHolding.setAgentStartTime(contractEntity.getStartDate());
            equipmentHolding.setAgentEndTime(contractEntity.getEndDate());
        }
        else if (Constant.ContractType.CHANNEL.getValue().equals(contractEntity.getType()))
        {
            equipmentHolding.setChannelOrgId(contractEntity.getYiOrgId());
            equipmentHolding.setChannelOrgName(contractEntity.getYiOrgName());
            equipmentHolding.setChannelRate(contractEntity.getBenifitRate()); // 渠道商分成比例
            equipmentHolding.setChannelStartTime(contractEntity.getStartDate());
            equipmentHolding.setChannelEndTime(contractEntity.getEndDate());
        }
        else if (Constant.ContractType.RENT.getValue().equals(contractEntity.getType()))
        {
            equipmentHolding.setRentOrgId(contractEntity.getYiOrgId());
            equipmentHolding.setRentOrgName(contractEntity.getYiOrgName());
            // 每天每台机器的收益 = （广告合同总金额 - 单台返利*机器台数） / 机器台数 , 保留两位小数点，舍去第三位小数点后的数字
            equipmentHolding.setRentPrice(calculateEachEquipEachDayAmount(contractEntity.getAmount(), contractEntity.getReturnAmount(), contractDays, equipCount)); // 广告商、租户租用价格,每天
            equipmentHolding.setRentStartTime(contractEntity.getStartDate());
            equipmentHolding.setRentEndTime(contractEntity.getEndDate());
        }
        else
        {
            throw new RRException("未知合同类型("+ contractEntity.getType() +")!");
        }

        // 设置需要更新收益信息的设备列表
        equipmentHolding.setEquipmentIds(contractEntity.getEquipmentIds());

        equipmentHoldingDao.updateByEquipmentIds(equipmentHolding);
    }
}
